import React, { useEffect, useState } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { View, Image, Map, Swiper, SwiperItem } from '@tarojs/components';
import './index.less';
import TitleBar from '@/src/components/titleBar';
import store from '@/src/store';
import { observer } from 'mobx-react-lite';
import { AtSearchBar } from 'taro-ui';
import StoreInfo from '@/src/components/storeInfo';
import InlinePanel from '@/src/components/inlinePanel';
import CitySelector from '@/src/components/citySelector';
import { nearbyListFun } from '@/src/common/method/nearbyFun';
import {
  convertCityToLALFun,
  getConversionFun,
} from '@/src/common/method/commonFun';
import PageBlank from '@/src/components/pageBlank';
import { ensureLocationAuth } from '@/src/utils/locationAuth';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';

//未给小程序开放位置权限时，用户位置在北京天安门
const DEFAULT_LOC = { latitude: 39.9087, longitude: 116.3975 };
const NearbyStores = () => {
  const [searchValue, setSearchValue] = useState<string>('');
  // userLoc 初始就设为天安门
  const [userLoc, setUserLoc] = useState(DEFAULT_LOC);
  // 附近门店标记
  const [markers, setMarkers] = useState<any[]>([]);
  // 城市名称
  const [city, setCity] = useState<any>('北京市');
  //城市编码
  const [cityCode, setCityCode] = useState<any>('610100');
  //店铺信息
  const [storesInfo, setStoresInfo] = useState<any>([]);
  //列表显示标志
  const [showStoresList, setShowStoresList] = useState<boolean>(false);
  //显示搜索城市列表
  const [showCityPanel, setShowCityPanel] = useState<boolean>(false);
  // 省份的code
  const [provinceCode, setProvinceCode] = useState<string>('');
  //当前店铺的index值
  const [selectedStoreIdx, setSelectedStoreIdx] = useState<number>(-1);
  // mapCenter 用来控制地图的中心点
  const [mapCenter, setMapCenter] = useState(DEFAULT_LOC);
  const [selectedIconPath, setSelectedIconPath] = useState<string>('');
  const [markIconPath, setMarkIconPath] = useState<string>('');
  // 是否显示附近门店信息卡片
  const [showStoresInfo, setShowStoresInfo] = useState<boolean>(false);
  // 地图的缩放范围
  const [mapScale, setMapScale] = useState<number>(12);
  // 是否显示距离：只有定位开启后才显示，没有定位权限不限制这个距离
  const [isShowDistance, setIsShowDistance] = useState<boolean>(false);
  useDidShow(() => {
    //监听网络状态
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });

  // 搜索附近门店
  const onChangeSearchValue = (value: string) => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setSearchValue(value);
    // 获取商店列表
    getNearbyList(
      { latitude: userLoc.latitude, longitude: userLoc.longitude },
      city,
      '',
      value
    );
    setShowStoresList(true);
  };

  // 跳转到选择城市页面
  const selectCity = () => {
    setShowCityPanel(true);
  };

  const dealStoreData = (list: any, selectedIdx: number) => {
    const ms = list.map((s: any, idx: number) => {
      const icon = idx === selectedIdx ? selectedIconPath : markIconPath;
      return {
        id: idx,
        latitude: s.latitude,
        longitude: s.longitude,
        iconPath: icon,
        width: idx === selectedIdx ? 30 : 20,
        height: idx === selectedIdx ? 36 : 29,
      };
    });
    setMarkers(ms);
  };

  // 获取附近门店列表
  const getNearbyList = (
    location: any = null,
    cityName: any = '',
    distanceThreshold: string = '',
    storeName: string = ''
  ) => {
    const params = {
      cityName: cityName || city,
      cityCode: cityCode,
      latitude: location ? location.latitude : userLoc.latitude,
      longitude: location ? location.longitude : userLoc.longitude,
      distanceThreshold,
      storeName,
    };
    nearbyListFun(params)
      .then((res: any) => {
        // 处理坐标选择问题
        if (res.stores && res.stores.length > 0) {
          dealStoreData(res.stores, selectedStoreIdx);
          setStoresInfo(res.stores);
        } else {
          setStoresInfo([]);
        }
      })
      .catch((err) => {
        console.log(err, 'err==');
      });
  };

  // 选择城市后的回调方法
  const selectedCity = (city: any, flag: string) => {
    setCity(city.areaName);
    setCityCode(city.areaCode);
    setProvinceCode(city.provinceCode);
    setShowStoresInfo(false);
    if (flag === 'mine') {
      //当用户定位到自己的位置，地图缩放到10KM范围内，如果选择的是市，显示全市范围
      setMapScale(12);
      setMapCenter({
        latitude: (city.location && city.location.latitude) || '',
        longitude: (city.location && city.location.longitude) || '',
      });
      setUserLoc({
        latitude: (city.location && city.location.latitude) || '',
        longitude: (city.location && city.location.longitude) || '',
      });
      setIsShowDistance(true);
    } else {
      setMapScale(9);
      convertCityToLALFun(city.areaName)
        .then((res: any) => {
          setMapCenter({ latitude: res.latitude, longitude: res.longitude });
        })
        .catch((e: any) => {});
    }

    // 获取商店列表
    getNearbyList(
      {
        latitude: (city.location && city.location.latitude) || userLoc.latitude,
        longitude:
          (city.location && city.location.longitude) || userLoc.longitude,
      },
      city.areaName,
      ''
    );
  };

  //查询全城市的商店列表
  const queryAllStores = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    // 获取商店列表
    getNearbyList(
      { latitude: userLoc.latitude, longitude: userLoc.longitude },
      city,
      ''
    );
    setShowStoresList(!showStoresList);
  };

  // 获取定位权限
  const getLocationFun = async () => {
    // 先确保授权（若被拒会弹自定义弹窗，引导去设置）
    const ok = await ensureLocationAuth();
    if (!ok) {
      // 未授权：保留默认位置，直接按默认拉数据
      console.warn('定位未授权');
      getNearbyList();
      return;
    }

    // 已授权 → 真正取定位
    try {
      const loc: any = await Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        highAccuracyExpireTime: 3000,
      });
      const location = `${loc.latitude},${loc.longitude}`;

      // 成功授权，使用真实位置
      setUserLoc({ latitude: loc.latitude, longitude: loc.longitude });
      setMapCenter({ latitude: loc.latitude, longitude: loc.longitude });
      setIsShowDistance(true);

      try {
        const res: any = await getConversionFun(location);
        setCity(res.city.areaName);
        setCityCode(res.city.areaCode);
        setProvinceCode(res.province.areaCode);
        store.commonStore.setCity(res.city.areaName);
        store.commonStore.setCityCode(res.city.areaCode);
        store.commonStore.setProvinceCode(res.province.areaCode);
        store.commonStore.setProvince(res.province.areaName);
        // 获取商店列表（用真实城市名）
        getNearbyList(
          { latitude: loc.latitude, longitude: loc.longitude },
          res.city.areaName
        );
      } catch (err: any) {
        console.log(err, 'err');
        // 反查失败也不阻塞门店列表
        getNearbyList(
          { latitude: loc.latitude, longitude: loc.longitude },
          city
        );
      }
    } catch {
      // 获取定位异常：回退默认
      console.warn('获取定位失败，使用默认位置');
      getNearbyList();
    }
  };

  useEffect(() => {
    dealStoreData(storesInfo, selectedStoreIdx);
  }, [storesInfo, selectedStoreIdx]);
  useEffect(() => {
    // getNearbyList();
  }, [city]);

  // 3. 小程序真机需要先通过 getImageInfo 拿到本地文件路径
  useEffect(() => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    getLocationFun();
    Taro.getImageInfo({
      src: 'https://file.linkcook.cn/image/wineMiniProgram/imgs/map/selectedStore.png',
    })
      .then((info) => setSelectedIconPath(info.path))
      .catch(() => {});
    Taro.getImageInfo({
      src: 'https://file.linkcook.cn/image/wineMiniProgram/imgs/map/markIcon.png',
    })
      .then((info) => setMarkIconPath(info.path))
      .catch(() => {});
  }, []);

  return (
    <View
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
      className="nearbyStores-container"
    >
      <TitleBar showLeftBack={true} title="附近门店"></TitleBar>
      <View className="nearbyStores-header">
        <View className="cities-container" onClick={selectCity}>
          <View className="cities">{city}</View>
          <Image
            src="https://file.linkcook.cn/image/wineMiniProgram/imgs/nearby/extend.png"
            className="expand"
          ></Image>
        </View>
        <View className="store-search">
          <AtSearchBar
            placeholder="搜索门店"
            className="custom-search-bar"
            value={searchValue}
            showActionButton={true}
            onChange={(val: string) => onChangeSearchValue(val)}
          />
        </View>
        <Image
          src={
            showStoresList
              ? 'https://file.linkcook.cn/image/wineMiniProgram/imgs/nearby/switchMap.png'
              : 'https://file.linkcook.cn/image/wineMiniProgram/imgs/nearby/switchList.png'
          }
          className="switch-to-list"
          onClick={queryAllStores}
        ></Image>
      </View>
      <InlinePanel
        visible={showCityPanel}
        mask={true}
        onClose={() => {
          setShowCityPanel(false);
        }}
        content={
          <CitySelector
            onSelect={selectedCity}
            onClose={() => {
              setShowCityPanel(false);
            }}
            initialProvinceCode={provinceCode}
            initialCityCode={cityCode}
          ></CitySelector>
        }
      ></InlinePanel>

      {showStoresList ? (
        <View
          className="stores-list-container"
          style={{
            height: `calc(100vh - ${store.commonStore.pageAreaTop}rpx - 96rpx)`,
            paddingBottom: `${store.commonStore.safeAreaBottom}rpx`,
          }}
        >
          {storesInfo.length > 0 ? (
            <View>
              {storesInfo.map((item: any, idx: number) => (
                <View className="storeinfo-item" key={idx}>
                  <StoreInfo
                    isHome={false}
                    storeInfo={item}
                    style={{ background: '#fff' }}
                    isShowDistance={isShowDistance}
                  />
                </View>
              ))}
            </View>
          ) : (
            <PageBlank
              visible={true}
              blank="https://file.linkcook.cn/image/wineMiniProgram/imgs/nearby/noStores.png"
              desc="抱歉，暂无门店"
            ></PageBlank>
          )}
        </View>
      ) : (
        <View>
          {/* 地图内容 */}
          <View>
            <Map
              className="map"
              style={{
                height: `calc(100vh - ${store.commonStore.pageAreaTop}rpx - 96rpx)`,
              }}
              // 点击 marker 时切换底部 Swiper
              onMarkerTap={(e: any) => {
                const idx = e.markerId;
                setSelectedStoreIdx(idx);
                setShowStoresInfo(true);
              }}
              latitude={mapCenter.latitude}
              longitude={mapCenter.longitude}
              markers={markers}
              onError={() => {}}
              scale={mapScale}
              showLocation={isShowDistance}
            />
          </View>
          {showStoresInfo && (
            <View
              className="nearby-store"
              style={{
                bottom: `calc(${store.commonStore.safeAreaBottom}rpx)`,
              }}
            >
              <Swiper
                className="store-swiper"
                current={selectedStoreIdx}
                indicatorDots={false}
                autoplay={false}
                circular={false}
                previousMargin="15px"
                nextMargin="15px"
                snapToEdge={false}
                onChange={(e) => {
                  setSelectedStoreIdx(e.detail.current);
                }}
                style={{
                  minHeight: '250px',
                  overflow: 'visible', // 允许溢出显示
                }}
              >
                {storesInfo.map((item: any, idx: number) => (
                  <SwiperItem key={idx} className="swiper-item">
                    <View className="storeinfo-item">
                      <StoreInfo
                        storeInfo={item}
                        isHome={false}
                        style={{ background: '#fff', margin: '0 4px' }}
                        isShowDistance={isShowDistance}
                      />
                    </View>
                  </SwiperItem>
                ))}
              </Swiper>
            </View>
          )}
        </View>
      )}
    </View>
  );
};
export default observer(NearbyStores);
